<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { CirclePlus, Apps, BrandAppstore } from '@vicons/tabler'
import ChatListGroup from './ChatListGroup.vue'
import ChatListItem from './ChatListItem.vue'
import { NScrollbar, NPopover, NIcon } from 'naive-ui'
import { getUserApps } from '@/service/api/userApp' // 假设我们有这个API函数
import type { AppGroup, AppItem } from '@/types/userApp'

const searchVal = ref('')
const appGroups = ref<AppGroup[]>([])

// selectedAppId
const props = defineProps<{
  selectedAppId: number
}>()

onMounted(async () => {
  try {
    const response = await getUserApps()
    appGroups.value = response.data
  } catch (error) {
    console.error('获取用户应用失败:', error)
  }
})

const filterList = computed(() => {
  if (!searchVal.value) {
    return {
      filteredGroups: appGroups.value
    }
  }

  const searchTerm = searchVal.value.toLowerCase()

  const filteredGroups = appGroups.value
    .map((group) => ({
      ...group,
      appList: group.appList.filter((item) => item.title.toLowerCase().includes(searchTerm))
    }))
    .filter((group) => group.appList.length > 0)

  return {
    filteredGroups
  }
})

const defaultAssistants = ref<AppItem[]>([
  {
    id: 0,
    title: '随便聊聊',
    desc: '',
    avatar: 'https://cdn.seovx.com/?mom=302',
    lastActiveAt: new Date().toISOString(),
    createAt: new Date().toISOString(),
    updateAt: new Date().toISOString(),
    type: 'chat',
    isTop: true,
    groupId: 0,
    tags: [],
    modelId: 'gpt-4'
  }
])

const emit = defineEmits<{
  (e: 'select-app', appId: number): void
}>()

const handleSelectApp = (appId: number) => {
  emit('select-app', appId)
}

const selectedAppId = computed(() => props.selectedAppId)
</script>

<template>
  <div class="h-full flex flex-col border border-r-solid border-r-#F0F0F0 bg-#FFFFFF rounded-t-2xl">
    <div class="flex items-center justify-between p-3 gap-3">
      <div class="flex items-center flex-1">
        <input
          placeholder="找不到？试试搜索"
          class="input-style rounded-lg hover:bg-gray-200 w-full transition-all duration-300 ease-in-out"
          type="text"
          v-model="searchVal"
        />
      </div>

      <n-popover trigger="click" raw :show-arrow="false" class="w-full rounded-xl">
        <template #trigger>
          <div
            class="flex items-center cursor-pointer p-5px rounded-lg ml-5px bg-gray-100 hover:bg-gray-200 text-[#787878]"
          >
            <n-icon size="20" :component="Apps"></n-icon>
          </div>
        </template>
        <div class="model-list rounded-md p-2 py-3 bg-white">
          <div class="rounded-md model-item cursor-pointer px-2 py-1 hover:bg-gray-100">
            <div class="flex items-center gap-1">
              <n-icon size="18" :component="CirclePlus"></n-icon>
              <span class="text-14px text-gray-500"> 创建聊天应用 </span>
            </div>
          </div>

          <div class="rounded-md model-item cursor-pointer px-2 py-1 hover:bg-gray-100">
            <div class="flex items-center gap-1">
              <n-icon size="18" :component="CirclePlus"></n-icon>
              <span class="text-14px text-gray-500"> 创建Agent应用 </span>
            </div>
          </div>
          <div class="rounded-md model-item cursor-pointer px-2 py-1 hover:bg-gray-100">
            <div class="flex items-center gap-1">
              <n-icon size="18" :component="CirclePlus"></n-icon>
              <span class="text-14px text-gray-500"> 创建流程应用 </span>
            </div>
          </div>
          <div class="h-[1px] w-full bg-gray-200 my-2"></div>
          <div class="rounded-md model-item cursor-pointer px-2 py-1 hover:bg-gray-100">
            <div class="flex items-center gap-1">
              <n-icon size="18" :component="BrandAppstore"></n-icon>
              <span class="text-14px text-gray-500"> 从应用市场导入 </span>
            </div>
          </div>
        </div>
      </n-popover>
    </div>
    <div class="w-full h-full flex flex-col flex-1">
      <div class="w-full px-3">
        <ChatListItem
          :showOption="false"
          v-for="item in defaultAssistants"
          :key="item.id"
          :data="item"
          :is-active="item.id === selectedAppId"
          @click="handleSelectApp(item.id)"
        ></ChatListItem>
      </div>
      <n-scrollbar class="px-3" style="height: calc(100vh - 52px - 69px - 50px); width: 100%">
        <chat-list-group
          v-for="group in filterList.filteredGroups"
          :key="group.id"
          v-model:group-name="group.title"
        >
          <ChatListItem
            v-for="item in group.appList"
            :key="item.id"
            :data="item"
            class="mt-2"
            :is-active="item.id === selectedAppId"
            @click="handleSelectApp(item.id)"
            :group-list="appGroups"
          ></ChatListItem>
        </chat-list-group>
      </n-scrollbar>
    </div>
  </div>
</template>

<style scoped lang="scss">
.input-style {
  padding: 8px;
  border: 1px solid #d9d9d9;
  outline: none;
  &:focus {
    outline: none;
  }
  &:hover {
    border-color: #000;
    background-color: #f5f5f5;
  }
}
</style>
